package com.atguigu.gmall.order.controller;

import com.alibaba.nacos.common.utils.StringUtils;
import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@RestController
@RequestMapping("api/order")
public class OrderApiController {

    // 注入远程调用
    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private CartFeignClient cartFeignClient;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    /**
     * 确认订单信息
     *
     * @param request
     * @return
     */
    @GetMapping("auth/trade")
    public Result<Map<String, Object>> trade(HttpServletRequest request) {

        // 获取用户id
        String userId = AuthContextHolder.getUserId(request);

        // 远程调用获取用户的地址信息
        List<UserAddress> userAddressList = userFeignClient.findUserAddressListByUserId(userId);

        // 获取已选择信息
        List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(userId);

        // 创建订单详情
        List<OrderDetail> detailArrayList = new ArrayList<>();
        // 判断
        if (cartCheckedList != null) {
            for (CartInfo cartInfo : cartCheckedList) {

                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setSkuId(cartInfo.getSkuId());
                orderDetail.setSkuName(cartInfo.getSkuName());
                orderDetail.setImgUrl(cartInfo.getImgUrl());
                orderDetail.setSkuNum(cartInfo.getSkuNum());
                orderDetail.setOrderPrice(cartInfo.getSkuPrice());

                detailArrayList.add(orderDetail);

            }
        }

        // 计算总金额
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderDetailList(detailArrayList);
        // 调用orderinfo中的一个方法 可以直接计算总价格
        orderInfo.sumTotalAmount();

        // 封装返回数据
        Map<String, Object> result = new HashMap<>();

        // 获取流水号
        String tradeNo = orderService.getTradeNo(userId);
        result.put("tradeNo", tradeNo);

        result.put("userAddressList", userAddressList);
        result.put("detailArrayList", detailArrayList);
        // 保存总金额
        result.put("totalNum", detailArrayList.size());
        result.put("totalAmount", orderInfo.getTotalAmount());

        // 返回数据
        return Result.ok(result);

    }

    /**
     * 提交订单
     *
     * @param orderInfo
     * @param request
     * @return
     */
    @PostMapping("auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request) {

        // 获取用户id'
        String userId = AuthContextHolder.getUserId(request);

        String tradeNo = request.getParameter("tradeNo");
        // 调用服务层比较方法
        boolean b = orderService.checkTradeCode(userId, tradeNo);
        if (!b) {
            return Result.fail().message("不能重复提交订单！");
        }


        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();

        if (orderDetailList != null) {
            for (OrderDetail orderDetail : orderDetailList) {
                // 使用异步编排来使用多线程，提高运行的速度
                // 创建一个List集合，类型为CompletableFuture
                List<CompletableFuture> completableFutureList = new ArrayList<>();
                // 创建一个List集合，用来存储提示的错误信息
                List<String> errorList = new ArrayList<>();
                // 创建异步编排线程，来使用多线程

                CompletableFuture<Void> skuNumCompletableFuture = CompletableFuture.runAsync(() -> {
                    Boolean res = this.orderService.checkStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
                    if (!res) {
                        errorList.add(orderDetail.getSkuName() + ":\t库存不足!");
                    }
                }, threadPoolExecutor);
                completableFutureList.add(skuNumCompletableFuture);
                CompletableFuture<Void> skuPriceCompletableFuture = CompletableFuture.runAsync(() -> {
                    // 比较价格，验证实时价格，如果价格不一样的话，提示用户
                    // 远程调用获取实时价格
                    String msg = "";
                    BigDecimal orderPrice = orderDetail.getOrderPrice();
                    BigDecimal price = productFeignClient.getSkuPrice(orderDetail.getSkuId());
                    if (orderPrice.compareTo(price) != 0) {
                        if (orderPrice.compareTo(price) > 0) {
                            msg = "降价" + orderPrice.subtract(price).abs();
                            errorList.add(orderDetail.getSkuName() + msg);
                        } else {
                            msg = "上涨" + orderPrice.subtract(price).abs();
                            errorList.add(orderDetail.getSkuName() + msg);
                        }
                    }
                }, threadPoolExecutor);
                completableFutureList.add(skuPriceCompletableFuture);
                // allOf 使用这个实现多线程，等待线程都执行完毕了才算完毕，后面必须使用.join
                CompletableFuture.allOf(completableFutureList.toArray(new CompletableFuture[completableFutureList.size()])).join();
                if (errorList.size() > 0) {
                    return Result.fail().message(StringUtils.join(errorList, ","));
                }

            }
        }

        orderInfo.setUserId(Long.parseLong(userId));

        // 调用service
        Long aLong = orderService.saveOrderInfo(orderInfo);

        // 删除流水号
        orderService.deleteTradeNo(userId);
        return Result.ok(aLong);
    }

    /**
     * 获取我的订单页面数据，分页查询
     *
     * @param page
     * @param limit
     * @param request
     * @return
     */
    @GetMapping("auth/{page}/{limit}")
    public Result<IPage<OrderInfo>> index(
            @ApiParam(name = "page", value = "当前页码", required = true)
            @PathVariable Long page,
            @ApiParam(name = "limit", value = "每页记录数", required = true)
            @PathVariable Long limit,
            HttpServletRequest request) {

        // 获取用户id
        String userId = AuthContextHolder.getUserId(request);

        if (userId != null) {

            // 创建分页对象
            Page<OrderInfo> orderInfoPage = new Page<>(page, limit);
            IPage<OrderInfo> iPage = orderService.getPage(orderInfoPage, userId);

            return Result.ok(iPage);
        }

        return Result.fail();

    }


    /**
     * 内部调用获取订单
     *
     * @param orderId
     * @return
     */
    @GetMapping("inner/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable(value = "orderId") Long orderId) {
        return orderService.getByIdOrderInfo(orderId.toString());
    }
}